const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');

const app = express();
const port = 3002;


const axios = require('axios');
const jwt = require('jsonwebtoken'); // 安装：npm install jsonwebtoken

// 微信配置（替换成你自己的）
const WX_APPID = 'wx19e9b38a905d62b0';
const WX_SECRET = 'e940542e7f2006514b33e2611fe5055c';

app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));

// 连接数据库
const pool = mysql.createPool({
    // host: '47.120.56.42',
    // user: 'xhs',
    // password: 'sNFinShnmGWYwRGP',
    // database: 'xhs',

    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'wx',

    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 登录接口
app.post('/api/login', async (req, res) => {
    const { code } = req.body;

    if (!code) {
        return res.status(400).json({ error: '缺少登录凭证 code' });
    }

    try {
        // 1. 请求微信服务器获取 openid 和 session_key
        const wxRes = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
            params: {
                appid: WX_APPID,
                secret: WX_SECRET,
                js_code: code,
                grant_type: 'authorization_code'
            }
        });

        const { openid, session_key } = wxRes.data;

        if (!openid || !session_key) {
            return res.status(400).json({ error: '微信登录失败', detail: wxRes.data });
        }

        // 2. 查询数据库是否已有该用户
        pool.query(
            'SELECT * FROM users WHERE openid = ?',
            [openid],
            (err, results) => {
                if (err) {
                    return res.status(500).json({ error: '数据库查询失败' });
                }

                let user = results[0];

                // 3. 没有用户就创建
                if (!user) {
                    pool.query(
                        'INSERT INTO users (openid, session_key) VALUES (?, ?)',
                        [openid, session_key],
                        (insertErr, insertResult) => {
                            if (insertErr) {
                                return res.status(500).json({ error: '用户创建失败' });
                            }

                            // 再次查询刚插入的用户
                            pool.query(
                                'SELECT * FROM users WHERE id = ?',
                                [insertResult.insertId],
                                (selectErr, selectResults) => {
                                    if (selectErr) {
                                        return res.status(500).json({ error: '用户数据获取失败' });
                                    }

                                    user = selectResults[0];
                                    generateAndReturnToken(user, res);
                                }
                            );
                        }
                    );
                } else {
                    // 用户已存在，更新 session_key（可选）
                    pool.query(
                        'UPDATE users SET session_key = ? WHERE openid = ?',
                        [session_key, openid],
                        () => {}
                    );

                    generateAndReturnToken(user, res);
                }
            }
        );
    } catch (error) {
        console.error('微信登录失败:', error);
        return res.status(500).json({ error: '微信登录失败' });
    }
});

// 生成 token 并返回
function generateAndReturnToken(user, res) {
    const token = jwt.sign({ userId: user.id, openid: user.openid }, 'your-secret-key', {
        expiresIn: '7d'
    });

    res.json({
        token,
        user: {
            id: user.id,
            openid: user.openid,
            nickname: user.nickname || '',
            avatar: user.avatar || ''
        }
    });
}

// 获取用户数据
app.get('/api/users', (req, res) => {
    pool.query('SELECT * FROM users', (error, results) => {
        if (error) return handleError(res, error, '用户数据');
        res.json(results);
    });
});

// 获取滚动列表数据 - 修复字段名问题
app.get('/api/roll', (req, res) => {
    // 明确选择字段并重命名以匹配前端期望
    pool.query('SELECT id, name, description, imageUrl, price FROM roll',
        (error, results) => {
            if (error) return handleError(res, error, '滚动列表');
            res.json(results);
        });
});

// 获取精选好物数据
app.get('/api/products', (req, res) => {
    pool.query('SELECT * FROM products', (error, results) => {
        if (error) return handleError(res, error, '精选好物');
        res.json(results);
    });
});

// 获取购物车数据
app.get('/api/shopping_cart', (req, res) => {
    pool.query('SELECT * FROM shopping_cart', (error, results) => {
        if(error) return handleError(res, error, '购物车');
        res.json(results)
    })
});

// 将购物车数据保存到数据库
app.post('/api/shopping_cart', (req, res) => {
    const { user_id, product_id, image_url, name, price, number } = req.body;

    // 计算总价
    const total_price = price * number;

    const query = `
        INSERT INTO shopping_cart (user_id, product_id, image_url, name, price, total_price, number)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    `;

    pool.query(query, [user_id, product_id, image_url, name, price, total_price, number], (error, results) => {
        if (error) return handleError(res, error, '添加购物车');

        res.json({ message: '商品已加入购物车', cart_id: results.insertId });
    });
});

// 移除购物车商品接口
app.post('/api/removeFromCart', (req, res) => {
    const { userId, productIds } = req.body;

    if (!userId || !Array.isArray(productIds) || productIds.length === 0) {
        return handleError(res, new Error('缺少必要参数或商品ID为空'), '移除购物车');
    }

    const placeholders = productIds.map(() => '?').join(',');
    const query = `
        DELETE FROM shopping_cart WHERE user_id = ? AND id IN (${placeholders})
    `;

    pool.query(query, [userId, ...productIds], (error, results) => {
        if(error) return handleError(res, error, '移除购物车');

        res.json({ message: '商品已从购物车中移除' });
    });
});

// 清空购物车接口 (新增，用于前端清空购物车按钮)
app.delete('/api/shopping_cart/clear/:userId', (req, res) => {
    const userId = req.params.userId;
    const query = 'DELETE FROM shopping_cart WHERE user_id = ?';

    pool.query(query, [userId], (error, results) => {
        if (error) {
            console.error('清空购物车失败:', error);
            return handleError(res, error, '清空购物车');
        }
        res.json({ message: '购物车已清空' });
    });
});

// 获取所有订单
app.get('/api/orders', (req, res) => {
    const sql = `SELECT * FROM orders`;
    pool.query(sql, (error, results) => {
        if(error) return res.status(500).json({ error: error.message });
        res.json(results);
    });
});

// 创建订单
app.post('/api/orders', (req, res) => {
    const { order_id, product_name, image_url, quantity, price, payment_method, status, customer_name, phone, address_detail } = req.body;
    const sql = `INSERT INTO orders (order_id, product_name, image_url, quantity, price, payment_method, status, customer_name, phone, address_detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

    pool.query(sql, [order_id, product_name, image_url, quantity, price, payment_method, status, customer_name, phone, address_detail], (error, results) => {
        if(error) return res.status(500).json({ error: error.message });
        res.status(201).json({ id: results.insertId });
    });
});

// 更新订单状态接口
app.put('/api/orders/:orderId', (req, res) => {
    const orderId = req.params.orderId;
    const { status } = req.body;

    if (!status) {
        return res.status(400).json({ error: '缺少状态参数' });
    }

    const sql = `UPDATE orders SET status = ? WHERE order_id = ?`;

    pool.query(sql, [status, orderId], (error, results) => {
        if (error) {
            console.error('更新订单状态失败:', error);
            return res.status(500).json({ error: '更新订单状态失败' });
        }

        if (results.affectedRows === 0) {
            return res.status(404).json({ error: '订单不存在' });
        }

        res.json({ message: '订单状态更新成功' });
    });
});

// 获取单个订单详情
app.get('/api/orders/:orderId', (req, res) => {
    const orderId = req.params.orderId;
    const sql = `SELECT * FROM orders WHERE order_id = ?`;

    pool.query(sql, [orderId], (error, results) => {
        if (error) {
            console.error('获取订单详情失败:', error);
            return res.status(500).json({ error: '获取订单详情失败' });
        }

        if (results.length === 0) {
            return res.status(404).json({ error: '订单不存在' });
        }

        res.json(results[0]);
    });
});

// 获取分类列表数据
app.get('/api/categories', (req, res) => {
    pool.query('SELECT * FROM categories', (error, results) => {
        if (error) return handleError(res, error, '分类列表');
        res.json(results);
    });
});

// 获取特定分类的物品数据
app.get('/api/categories/:categoryId/items', (req, res) => {
    const categoryId = req.params.categoryId;
    const query = 'SELECT id, name, CAST(price AS DECIMAL(10,2)) AS price, image_url, stock FROM category_items WHERE category_id = ?';

    pool.query(query, [categoryId], (error, results) => {
        if (error) {
            console.error('获取分类物品失败:', error);
            return res.status(500).json({ error: '数据库查询失败' });
        }

        // 确保所有价格都是数字类型
        const formattedResults = results.map(item => ({
            ...item,
            price: Number(item.price)
        }));

        res.json(formattedResults);
    });
});

// 添加获取所有物品的接口
app.get('/api/category_items', (req, res) => {
    pool.query('SELECT * FROM category_items', (error, results) => {
        if (error) {
            console.error('获取所有物品失败:', error);
            return res.status(500).json({ error: '获取所有物品失败' });
        }

        // 格式化返回数据
        const formattedResults = results.map(item => ({
            id: item.id,
            name: item.name,
            price: item.price,
            image_url: item.image_url,
            stock: item.stock,
            category_id: item.category_id
        }));

        res.json(formattedResults);
    });
});

// 错误处理函数 (放在这里确保所有路由都能访问)
function handleError(res, error, dataType) {
    console.error(`获取${dataType}失败:`, error);
    return res.status(500).json({ error: `数据库查询失败: ${error.message}` });
}

app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});